#region License
// Product:
// MCM (Message-Command-Message)
// mcm-framework.net
// 
// Author:
// Pawel Idzikowski
// Cologne, Germany
// idzikowski@polenter.com
// 
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the author(s) be held liable for any damages arising from
// the use of this software.
// 
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 
//     1. The origin of this software must not be misrepresented; you must not
//       claim that you wrote the original software. If you use this software
//       in a product, an acknowledgment in the product documentation would be
//       appreciated but is not required.
// 
//     2. Altered source versions must be plainly marked as such, and must not
//       be misrepresented as being the original software.
// 
//     3. This notice may not be removed or altered from any source distribution.
// 
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace Polenter.Mcm
{
    /// <summary>
    /// Log is configured in app.config
    /// Log.Default ist the default log for the whole framework
    /// </summary>
    internal class McmLog
    {
        private static readonly List<TraceSource> _traceSources = new List<TraceSource>();
        private static McmLog _default;
        private static readonly object _defaultLocker = new object();
        private readonly TraceSource _traceSource;

        public McmLog(string traceSourceName)
        {
            _traceSource = getTraceSource(traceSourceName);
        }

        public TraceSource TraceSource
        {
            get { return _traceSource; }
        }

        public static McmLog Default
        {
            get
            {
                if (_default == null)
                {
                    InitializeDefault("Log");
                }
                return _default;
            }
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        private static TraceSource getTraceSource(string traceSourceName)
        {
            if (traceSourceName == null) throw new ArgumentNullException("traceSourceName");
            foreach (TraceSource traceSource in _traceSources)
            {
                if (StringComparer.CurrentCultureIgnoreCase.Compare(traceSourceName, traceSource.Name) == 0)
                {
                    return traceSource;
                }
            }

            var source = new TraceSource(traceSourceName);
            _traceSources.Add(source);
            return source;
        }

        public static void InitializeDefault(string traceSourceName)
        {
            lock (_defaultLocker)
            {
                if (_defaultLocker != null)
                {
                    throw new InvalidOperationException("Log.Default can be only once initialized.");
                }
                _default = new McmLog(traceSourceName);
            }
        }

        public void WriteInfo(string text)
        {
            _traceSource.TraceInformation(text);
        }

        public void WriteVerbose(string text)
        {
            _traceSource.TraceData(TraceEventType.Verbose, 0, text);
        }

        public void WriteWarning(string text)
        {
            _traceSource.TraceData(TraceEventType.Warning, 0, text);
        }

        public void WriteError(Exception error)
        {
            _traceSource.TraceData(TraceEventType.Error, 0, error);
        }

        public void WriteError(string text)
        {
            _traceSource.TraceData(TraceEventType.Error, 0, text);
        }

        public void Write(string text, TraceEventType traceEventType)
        {
            _traceSource.TraceData(traceEventType, 0, text);
        }

        /// <summary>
        /// Informs about the method, where it was called
        /// </summary>
        /// <param name="text"></param>
        /// <param name="eventType"></param>
        public void WriteCallingMethod(string text, TraceEventType eventType)
        {
            if (!_traceSource.Switch.ShouldTrace(eventType))
            {
                return;
            }
            StackFrame frame = new StackTrace(1).GetFrame(0);
            MethodBase method = frame.GetMethod();
            string declaringTypeName = method.DeclaringType.Name;
            string methodName;
            if (declaringTypeName.Equals(_traceSource.Name))
            {
                // TypeName is not necessary
                methodName = string.Format("{0}() [{1}]", method.Name, text);
            }
            else
            {
                // TypeName is needed
                methodName = string.Format("{0}.{1}() [{2}]", declaringTypeName, method.Name, text);
            }
            _traceSource.TraceData(eventType, 0, methodName);
        }

        public bool ShouldWrite(TraceEventType eventType)
        {
            return _traceSource.Switch.ShouldTrace(eventType);
        }
    }
}